<?php

namespace app\common\model\points;

use app\common\exception\BaseException;
use think\Cache;
use app\common\model\BaseModel;

/**
 * 商品分类模型
 * Class Category
 * @package app\common\model
 */
class Category extends BaseModel
{
    protected $name = 'points_category';

    /**
     * 分类类型
     * @param $value
     * @return mixed
     */
    public function getCategoryTypeAttr($value)
    {
        $status = [10 => '积分', 20 => '返现劵'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 所有分类
     * @return mixed
     */
    public static function getALL()
    {
        $model = new static;
        if (!Cache::get('points_category_' . $model::$wxapp_id)) {
            $data = $model->order(['sort' => 'asc', 'create_time' => 'asc'])->select();
            $all = !empty($data) ? $data->toArray() : [];
            Cache::tag('cache')->set('points_category_' . $model::$wxapp_id, $all);
        }
        return Cache::get('points_category_' . $model::$wxapp_id);
    }

    /**
     * 积分分类
     * @return mixed
     */
    public static function getPointsALL()
    {
        $model = new static;
        if (!Cache::get('api_points_category_' . $model::$wxapp_id)) {
            $data = $model->where('category_type', '=', 10)->order(['sort' => 'asc', 'create_time' => 'asc'])->select();
            $all = !empty($data) ? $data->toArray() : [];
            Cache::tag('cache')->set('api_points_category_' . $model::$wxapp_id, $all);
        }
        return Cache::get('api_points_category_' . $model::$wxapp_id);
    }

    /**
     * 优惠券分类
     * @return mixed
     */
    public static function getCouponALL()
    {
        $model = new static;
        if (!Cache::get('api_coupon_category_' . $model::$wxapp_id)) {
            $data = $model->where('category_type', '=', 20)->order(['sort' => 'asc', 'create_time' => 'asc'])->select();
            $all = !empty($data) ? $data->toArray() : [];
            Cache::tag('cache')->set('api_coupon_category_' . $model::$wxapp_id, $all);
        }
        return Cache::get('api_coupon_category_' . $model::$wxapp_id);
    }

    /**
     * 获取对应分类
     * @param $goods_type
     * @return mixed
     * @throws BaseException
     */
    public static function getCategoryByGoodsType($goods_type)
    {
        if (!in_array($goods_type, [10, 20])) {
            throw new BaseException(['msg' => '参数不合法']);
        }
        if ($goods_type == 10) {
            return self::getPointsALL();
        }
        return self::getCouponALL();
    }

}
